package com.ytjj.qmyx.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.annotation.OperLog;
import com.ytjj.qmyx.admin.annotation.oplog.OperationLogger;
import com.ytjj.qmyx.admin.annotation.oplog.OperationProductLogger;
import com.ytjj.qmyx.admin.annotation.oplog.annotation.OperationLog;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.constants.SysLogConstants;
import com.ytjj.qmyx.admin.model.Role;
import com.ytjj.qmyx.admin.model.YxProduct;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.request.bankerProduct.SupplyChainProductUpdateStatusRequest;
import com.ytjj.qmyx.admin.model.response.ProductModelResponse;
import com.ytjj.qmyx.admin.model.response.ProductStatisticsResponse;
import com.ytjj.qmyx.admin.model.response.SupplyProductListResponse;
import com.ytjj.qmyx.admin.service.AdminService;
import com.ytjj.qmyx.admin.service.MemberService;
import com.ytjj.qmyx.admin.service.ProductService;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.users.client.CircleClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品管理
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private MemberService memberService;
    @Autowired
    private CircleClient circleClient;

    @Autowired
    private SupplyApiConfig supplyApiConfig;

    @Autowired
    private ChannelProductService channelProductService;

    @Resource
    private ProductMapper productMapper;

    @Autowired
    private AdminService adminService;

    /**
     * 受限制角色id(成本、供货价、供应商仓库地址)
     */
    @Value("${limit.roleId:2,13}")
    private String limitRoleId;


    /**
     * 根据条件查询商品（销售端商品列表）
     *
     * @return
     */
    @PostMapping(value = "/list")
    public CommonResult list(@RequestBody ProductRequest product) {
        return CommonResult.success(productService.selectList(product));
    }

    /**
     * 根据条件查询商品(供应链商品列表)
     *
     * @return
     */
    @PostMapping(value = "/supplyProductlist")
    public CommonResult supplyProductlist(@RequestBody ProductRequest request) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/all", JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("接口出错");
        }
        CommonResult<CommonPage<SupplyProductListResponse>> result = JSONObject.parseObject(resultJson, new TypeReference<CommonResult<CommonPage<SupplyProductListResponse>>>(){});
        if (result!=null && result.getData() != null) {
            List<Integer> productIdList = result.getData().getList().stream().filter(item -> item.getId() != null).map(SupplyProductListResponse::getId).collect(Collectors.toList());
            List<ProductReviews> productReviews = new ArrayList<>();
            if (!CollectionUtils.isEmpty(productIdList)) {
                productReviews = productService.getProductReviews(productIdList);
            }

            //是否限制展示成本价和供货价角色
            boolean isLimitRole = checkIsLimitRole();
            CommonPage<SupplyProductListResponse> data = result.getData();
            for (SupplyProductListResponse response:data.getList()){
                if (!CollectionUtils.isEmpty(productReviews)) {
                    List<ProductReviews> collect = productReviews.stream().filter(item -> item.getProductId().equals(response.getId())).collect(Collectors.toList());
                    response.setProductReviews(collect);
                }
                if (isLimitRole) {
                    response.setCostPrice(BigDecimal.ZERO);
                    response.setSupplyPrice(BigDecimal.ZERO);
                }
            }
        }
        return result;
    }

    /**
     * 添加商品评论
     * @return
     */
    @PostMapping(value = "/addProductReviews")
    public CommonResult addProductReviews(@RequestBody ProductReviewsAddRequest request) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/addProductReviews", JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("接口出错");
        }
        return CommonResult.success();
    }


    /**
     * 修改商品评论
     * @return
     */
    @PostMapping(value = "/updateProductReviews")
    public CommonResult updateProductReviews(@RequestBody ProductReviewsUpdateRequest request) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/updateProductReviews", JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("接口出错");
        }
        return CommonResult.success();
    }



    public boolean checkIsLimitRole() {
        boolean isLimitRole = false;
        try {
            String userId = UserUtil.getPrincipal();
            List<Role> role = adminService.getRoleByEmail(userId);
            log.info("====currentUserRoldId={}", role.toString());
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(role) && !com.alibaba.excel.util.StringUtils.isEmpty(limitRoleId)) {
                List<String> limitRoleIds = Arrays.asList(limitRoleId.split(","));
                if (limitRoleIds.contains(String.valueOf(role.get(0).getId()))) {
                    isLimitRole = true;
                }
            }
        }catch (Exception e) {
            log.error("{}",e);
        }
        return isLimitRole;
    }


    /**
     * 获取所有销售端
     * @return
     */
    @GetMapping("/queryAllShopInfo")
    public CommonResult queryAllShopInfo() {
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/allShopInfo", new HashMap<>(), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("接口出错");
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }


    /**
     * 供应链商品上架
     *
     * @param request
     * @return
     */
    @PostMapping("/putOrOutToSelection")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "供应链商品上架/下架")
    public CommonResult putOrOutToSelection(@RequestBody SupplyChainProductUpdateStatusRequest request) {

        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", request.getIds());
            map.put("batch", 0);
            if (request.getStatus().equals(0)) {
                map.put("msg", "商品上架");
            } else if (request.getStatus().equals(1)) {
                map.put("msg", "商品下架");
            } else {
                map.put("msg", "商品上架/下架/移除");
            }
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装供应链商品上架/下架日志信息异常{}", e);
        }

        if (request.getStatus().equals(0)){
            List<Integer> ids = request.getIds();
            ids.stream().forEach(id ->{
                ProductExample productExample = new ProductExample();
                productExample.createCriteria().andSupplyProductIdEqualTo(id).andStatusEqualTo((byte) 1);
                List<Product> products = productMapper.selectByExample(productExample);
                if (!CollectionUtils.isEmpty(products)){
                    products.stream().forEach(item ->{
                        channelProductService.putOutChannelProduct(item.getId(),2,request.getOutOfSelection());
                    });
                }
            });
        }

        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/productStatusUpdate", JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("接口出错");
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }

    @PostMapping("/circle/list")
    public CommonResult circleList(@RequestBody ProductRequest product) {
        com.ytjj.qmyx.users.model.circle.ProductRequest productRequest = new com.ytjj.qmyx.users.model.circle.ProductRequest();
        BeanUtils.copyProperties(product, productRequest);
        return circleClient.circleProductList(productRequest);
    }

    /**
     * 商品列表下载
     *
     * @param product
     * @return
     */
    @PostMapping(value = "/download")
    public CommonResult download(@RequestBody ProductRequest product) {
        CommonPage<ProductModelResponse> pageList = productService.downloadList(product);
        return CommonResult.success(pageList);
    }

    /**
     * 查看一级分类
     */
    @GetMapping("/getTopCategoryList")
    public CommonResult getTopCategoryList() {
        return CommonResult.success(productService.getTopCategoryList());
    }

    @GetMapping("/getChildCategoryList")
    public CommonResult getChildCategoryList(@RequestParam("pid") Integer pid) {
        return CommonResult.success(productService.getChildCategoryList(pid));
    }

    /**
     * 查询店家自己的商品（店家接口）
     *
     * @return
     */
    @GetMapping(value = "/getListByBankerId")
    public CommonResult getListByBankerId() {
        Banker banker = memberService.getBanker();
        List<Product> products = productService.getListByBankerId(banker.getId());
        return CommonResult.success(products);
    }


    /**
     * @Description 查询所有商品版块信息
     *
     * 
     * @Version 1.0
     **/
    @GetMapping("/getAllForumProductInfo")
    public CommonResult getAllForumProductInfo() {
        return CommonResult.success(productService.getAllForumProductInfo());
    }


    /**
     * @Description 搜索品牌商
     *
     * 
     * @Version 1.0
     **/
    @GetMapping("/getBrandList")
    public CommonResult getBrandList(@RequestParam("bankerName") String bankerName) {
        return CommonResult.success(productService.getBrandList(bankerName));
    }

    /**
     * @Description 添加品牌商
     *
     * 
     * @Version 1.0
     **/
    @GetMapping("/addBrand")
    public CommonResult addBrand(@RequestParam(value = "bankerId", required = true) Integer bankerId) {
        productService.addBrand(bankerId);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * @Description 更新排序
     *
     * 
     * @Version 1.0
     **/
    @GetMapping("/updateSort")
    public CommonResult updateSort(@RequestParam("id") Integer id,
                                   @RequestParam("sort") Integer sort) {
        productService.updateSort(id, sort);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * @Description 移除供应商
     *
     * 
     * @Version 1.0
     **/
    @GetMapping("/removeBrand")
    public CommonResult removeBrand(@RequestParam("id") Integer id) {
        productService.removeBrand(id);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * @Description 获取添加的品牌商
     *
     * 
     * @Version 1.0
     **/
    @GetMapping("/getBrandUpList")
    public CommonResult getBrandUpList(@RequestParam(value = "bankerName", required = false) String bankerName,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        return CommonResult.page(productService.getBrandUpList(bankerName, pageSize, pageNum));
    }

    /**
     * 根据id查询商品信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/getProduct")
    public CommonResult<Product> productInfosById(@RequestParam Integer id) {
        Product product = productService.productInfosById(id);
        return CommonResult.success(product);
    }

    /**
     * 根据供应商商品id查询商品信息
     *
     * @param supplyProductId
     * @return
     */
    @GetMapping(value = "/getSupplyProduct")
    public CommonResult<YxProduct> getSupplyProduct(@RequestParam Integer supplyProductId) {
        YxProduct product = productService.getSupplyProduct(supplyProductId);
        return CommonResult.success(product);
    }


    /**
     * 创建商品表（后续逻辑需要处理/补充）
     *
     * @param addProductRequest
     * @return
     */
    @PostMapping(value = "/create")
    @OperLog(operModule = "店家商品模块", operDesc = "创建商品表", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult create(@RequestBody AddProductRequest addProductRequest) {
        int count = productService.create(addProductRequest);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 修改商品表（后续逻辑需要处理/补充）
     *
     * @param editProductRequest
     * @return
     */
    @PostMapping(value = "/update")
    @OperLog(operModule = "店家商品模块", operDesc = "修改商品表", operType = SysLogConstants.OPERATION_UPDATE)
    public CommonResult update(@RequestBody EditProductRequest editProductRequest) {
        int count = productService.update(editProductRequest);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }


    /**
     * 根据商品id查询选择的sku属性key
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/selectSkuKeysbyId")
    public CommonResult selectSkuKeysbyId(@RequestParam Integer id) {
        Map<String, Object> datas = productService.selectSkuKeysbyId(id);
        return CommonResult.success(datas);
    }

    /**
     * 商品上架/下架/移除
     *
     * @param id
     * @return
     */
    @RequiresPermissions("product:updateStatus")
    @GetMapping(value = "/updateStatus")
//    @OperLog(operModule = "商品模块", operDesc = "商品上架/下架", operType = SysLogConstants.OPERATION_UPDATE)
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "商品上架/下架/移除")
    public CommonResult updateStatus(@RequestParam(value = "id") Integer id,
                                     @RequestParam(value = "status") Byte status,
                                     @RequestParam(required = false, value = "downRemark") String downRemark) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", id);
            map.put("batch", 0);
            if (status == 1) {
                map.put("msg", "商品上架");
            } else if (status == 2) {
                map.put("msg", "商品下架");
            } else if (status == 3) {
                map.put("msg", "商品移除");
            } else {
                map.put("msg", "商品上架/下架/移除");
            }
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.updateStatus(id, status, downRemark);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }

    }

    /**
     * 根据id删除商品
     *
     * @param id
     * @return
     */
    @PostMapping(value = "/delete")
//    @OperLog(operModule = "店家商品模块", operDesc = "根据id删除商品", operType = SysLogConstants.OPERATION_UPDATE)
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_DELETE, desc = "商品删除")
    public CommonResult delete(@RequestParam Integer id) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "商品删除");
            map.put("id", id);
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.delete(id);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 批量修改商品规格中的价格、库存、直接购买价
     * 同时商品的总库存需同步
     *
     * @param batchRequest
     * @return
     */
    @PostMapping(value = "/updatePriceStock")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "修改商品规格参数")
    public CommonResult updatePriceStock(@RequestBody ProductBatchRequest batchRequest) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "修改商品规格参数");
            map.put("id", batchRequest.getProductId());
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.updatePriceStock(batchRequest.getProductId(), batchRequest.getPrice(), batchRequest.getStock(), batchRequest.getCurPrice());
        //批量修改库存后--同步商品总库存数
        if (count > 0 && batchRequest.getStock() != null) {
            int allCount = count * batchRequest.getStock();
            productService.updateStock(batchRequest.getProductId(), allCount);
        }
        return CommonResult.success(count);
    }

    /**
     * 删除规格属性
     */
    @GetMapping("/deleteProductSpec")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_DELETE, desc = "删除商品规格属性")
    public CommonResult deleteProductSpec(@RequestParam("id") Integer id) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "删除商品规格属性");
            map.put("id", id);
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        productService.deleteProductSpec(id);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    // ------------------------------------------------------------------------添加活动-----------------------------------------------------------------------------

    /**
     * 添加活动
     *
     * @param productActivity
     * @return
     */
    @PostMapping(value = "/addActivity")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_ADD, desc = "商品添加活动")
    public CommonResult addActivity(@RequestBody ProductActivityRequest productActivity) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "商品添加活动");
            map.put("id", productActivity.getProductId());
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.addActivity(productActivity);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 根据栏目类型查询栏目
     *
     * @param type
     * @return
     */
    @GetMapping(value = "/getColumnByType")
    public CommonResult<List<ActivityColumn>> getColumnByType(@RequestParam String type) {
        List<ActivityColumn> activityColumn = productService.getColumnByType(type);
        return CommonResult.success(activityColumn);
    }

    /**
     * 获取栏目列表
     */
    @GetMapping("/getColumnList")
    public CommonResult getColumnList() {
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/columnList", null, supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("接口出错");
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }


    /**
     * 查询商品专区列表（作废接口）
     *
     * @param productSpecialRequest
     * @return
     */
    @PostMapping(value = "/getProductSpecial")
    public CommonResult getProductSpecial(@RequestBody ProductSpecialRequest productSpecialRequest) {
        CommonPage<ProductSpecial> pageList = productService.getProductSpecial(productSpecialRequest);
        return CommonResult.success(pageList);
    }

    // --------------------------------------------------------商品规格/图片---------------------------------------------------------------------


    /**
     * 查询商品规格表列表
     *
     * @param ProductSpecRequest
     * @return
     */
    @PostMapping(value = "/getProductSpec")
    public CommonResult getProductSpec(@RequestBody ProductSpecRequest ProductSpecRequest) {
        CommonPage<ProductSpec> pageList = productService.getProductSpec(ProductSpecRequest);
        return CommonResult.success(pageList);
    }

    /**
     * 商品规格一键修改图片
     *
     * @param productSpecRequest
     * @return
     */
    @PostMapping(value = "/updateProductSpecImg")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "修改商品规格图片")
    public CommonResult updateProductSpecImg(@RequestBody ProductSpecRequest productSpecRequest) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "修改商品规格图片");
            map.put("id", productSpecRequest.getProductId());
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.updateProductSpecImg(productSpecRequest);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 修改商品规格列表
     *
     * @param productSpec
     * @return
     */
    @PostMapping(value = "/updateProductSpec")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "修改商品规格")
    public CommonResult updateProductSpec(@RequestBody ProductSpec productSpec) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "修改商品规格");
            map.put("id", productSpec.getProductId());
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.updateProductSpec(productSpec);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 查询商品图片列表
     *
     * @param productImgRequest
     * @return
     */
    @PostMapping(value = "/getProductImgs")
    public CommonResult getProductImgs(@RequestBody ProductImgRequest productImgRequest) {
        CommonPage<ProductImg> pageList = productService.getProductImgs(productImgRequest);
        return CommonResult.success(pageList);
    }

    // ------------------------------------------------------------------推荐信息-------------------------------------------------------------------------------------

    /**
     * 查询商品推荐信息
     *
     * @param productId
     * @return
     */
    @RequiresPermissions("product:getProductMatching")
    @GetMapping(value = "/getProductMatching")
    public CommonResult getProductMatching(@RequestParam Integer productId) {
        ProductMatching productMatching = productService.getProductMatching(productId);
        return CommonResult.success(productMatching);
    }


    /**
     * 修改商品推荐信息
     *
     * @param productMatching
     * @return
     */
    @PostMapping(value = "/updateProductMatching")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_ADD, desc = "修改商品推荐信息")
    public CommonResult updateProductMatching(@RequestBody ProductMatching productMatching) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "修改商品推荐信息");
            map.put("id", productMatching.getProductId());
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.updateProductMatching(productMatching);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }


    /**
     * 批量set stock
     *
     * @param stock
     * @return
     */
    @GetMapping(value = "/updateStockBatch")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "批量设置商品库存")
    public CommonResult updateStockBatch(@RequestParam Integer stock) {
        OperationLogger.log("商品批量设置库存");
        int count = productService.updateStockBatch(stock);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    // ------------------------------------------------------------------选择置顶/取消置顶-------------------------------------------------------------------------------------

    /**
     * 商品是否置顶
     *
     * @param product
     * @return
     */
    @RequiresPermissions("product:isHomeFlag")
    @PostMapping("/isHomeFlag")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "商品是否置顶")
    public CommonResult isHomeFlag(@RequestBody ProductRequest product) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "商品是否置顶 0否 1是" + product.getHomeFlag());
            map.put("id", product.getId());
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        int count = productService.isHomeFlag(product.getId(), product.getHomeFlag());
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    // ------------------------------------------------------------------商品统计表-------------------------------------------------------------------------------------

    /**
     * 查询商品统计表
     *
     * @param productStatisticsRequest
     * @return
     */
    @PostMapping("/queryProductStatistics")
    public CommonResult queryProductStatistics(@RequestBody ProductStatisticsRequest productStatisticsRequest) {
        CommonPage<ProductStatisticsResponse> pageList = productService.queryProductStatistics(productStatisticsRequest);
        return CommonResult.success(pageList);
    }

    /**
     * 导出excel 前端导出
     *
     * @param request
     * @return
     */
    @PostMapping("/exportOrdersExcel")
    public CommonResult exportOrdersExcel(@RequestBody ProductStatisticsRequest request) {
        List<ProductStatisticsResponse> list = productService.exportOrdersExcel(request);
        return CommonResult.success(list);
    }


    // ------------------------------------------- 一键操作 --------------------------------------------------

    /**
     * 一键操作 商品-->活动商品
     *
     * @param easyShuttleRequest
     * @return
     */
    @PostMapping("/easyShuttle")
    public CommonResult easyShuttle(@RequestBody EasyShuttleRequest easyShuttleRequest) {
        return CommonResult.success(productService.easyShuttle(easyShuttleRequest));
    }


    // ---------------------------------------  同步商品规格--直接购买价----------------------------------
    @PostMapping("/syncSpecInfo")
    public CommonResult syncSpecInfo() {
        return CommonResult.success(productService.syncSpecInfo());
    }


    @PostMapping("/getSmallProductList")
    public CommonResult getSmallProductList(@RequestBody NewProductRequest newProductRequest) {
        return CommonResult.success(productService.getSmallProductList(newProductRequest));
    }

    @PostMapping("/updateProductActivityType")
    public CommonResult updateProductActivityType(@RequestBody NewProductRequest newProductRequest) {
        productService.updateProductActivityType(newProductRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 编辑地区商品的活动栏目
     */
    @PostMapping("/updateProductActivityTypeForProvince")
    public CommonResult updateProductActivityTypeForProvince(@RequestBody NewProductRequest newProductRequest) {
        productService.updateProductActivityTypeForProvince(newProductRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    @PostMapping("/updateProduct")
    public CommonResult updateProduct(@RequestBody UpdateProductRequest updateProductRequest) {
        productService.updateProduct(updateProductRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * @Description 移除活动商品
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/removeActivityProduct")
    public CommonResult removeActivityProduct(@RequestParam("id") Integer id) {
        productService.removeActivityProduct(id);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * @Description 移除活动商品
     *
     *
     * @Version 1.0
     **/
    @PostMapping("/batchRemoveActivityProduct")
    public CommonResult batchRemoveActivityProduct(@RequestBody List<Integer> productIds) {
        if(CollectionUtils.isEmpty(productIds)){
            throw new ApiException("请选择一条数据！");
        }
        productIds.forEach(e->{
            productService.removeActivityProduct(e);
        });
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 商品管理-打回
     *
     * @param id
     * @param message
     * @return
     */
    @RequiresPermissions("product:returnBackProduct")
    @GetMapping("/returnBackProduct")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "商品打回")
    public CommonResult returnBackProduct(@RequestParam("id") Integer id, @RequestParam("message") String message) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("msg", "商品打回" + message);
            map.put("id", id);
            map.put("batch", 0);
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装日志信息异常{}", e);
        }
        return CommonResult.success(productService.returnBackProduct(id, message));
    }

    /**
     * 供应链-商品移除
     * @param id
     * @param message
     * @return
     */
    @GetMapping("/removeSupplychainProduct")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "商品移除")
    public CommonResult removeSupplychainProduct(@RequestParam("id") Integer id, @RequestParam(value = "message", required = false) String message) {
        return productService.removeSupplychianProduct(id, message);
    }

    /**
     * 秒杀页 批量操作extra日期
     *
     * @param productLifeRequest
     * @return
     */
    @PostMapping("/updateSeckillDate")
    public CommonResult updateSeckillDate(@RequestBody ProductLifeRequest productLifeRequest) {
        return CommonResult.success(productService.seckillDate(productLifeRequest.getIds(), productLifeRequest.getExtra()));
    }


    // --------------------------------------- 生活馆模块 ----------------------------------

    @PostMapping("/getProductLifeByType")
    public CommonResult getProductLifeByType(@RequestBody ProductLifeRequest productLifeRequest) {
        return CommonResult.success(productService.getProductLifeByType(productLifeRequest));
    }

    @PostMapping("/addProductLife")
    public CommonResult addProductLife(@RequestBody ForumAddRequest forumAddRequest) {
        return CommonResult.success(productService.addProductLife(forumAddRequest));
    }


    // -------------------------------------- 修改单个商品的活动参数 --------------------------

    @PostMapping("/updateProductParam")
    public CommonResult updateProductParam(@RequestBody ProductParamRequest productParamRequest) {
        return CommonResult.success(productService.updateProductParam(productParamRequest));
    }

    @GetMapping("/buyerList")
    public String buyerList() {
        return productService.buyerList();
    }

    /**
     * 获取全部助理
     *
     * @return
     */
    @GetMapping("/assistantList")
    public String assistantrList() {
        return productService.assistantList();
    }

    // --------------------------------------- 生活馆推荐 -------------------------------------

    @PostMapping("/getLifeHomeFlagList")
    public CommonResult getLifeHomeFlagList(@RequestBody LifeHomeFlagRequest lifeHomeFlagRequest) {
        return CommonResult.success(productService.getLifeHomeFlagList(lifeHomeFlagRequest));
    }

    @GetMapping("/chooseHomeFlag")
    public CommonResult chooseHomeFlag(@RequestParam String platformType, @RequestParam String productName) {
        return CommonResult.success(productService.chooseHomeFlag(platformType, productName));
    }

    @GetMapping("/addHomeFlag")
    public CommonResult addHomeFlag(@RequestParam Integer id) {
        productService.homeFlagTrue(id);
        return CommonResult.success();
    }

    @GetMapping("/removeHomeFlag")
    public CommonResult removeHomeFlag(@RequestParam Integer id) {
        productService.homeFlagFalse(id);
        return CommonResult.success();
    }

    /**
     * 把商品详情图片转到商品表中
     */
    @GetMapping("/updateImgToTable")
    public CommonResult updateImgToTable(){
        return productService.updateImgToTable();
    }
}
